package com.example.wanandroid_copy2.ui.search.viewmodel

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.example.wanandroid_copy2.common.BaseResponse
import com.example.wanandroid_copy2.common.constant.Constant
import com.example.wanandroid_copy2.ui.article.viewmodel.ArticleViewModel
import com.example.wanandroid_copy2.ui.search.dao.*

class SearchViewModel(application: Application) : ArticleViewModel<SearchRepository>(application) {

    val searchLiveData = MutableLiveData<BaseResponse<SearchResultRsp>>()
    val hotSearchLiveData = MutableLiveData<BaseResponse<List<HotSearchRsp>>>()
    val mSearchHistory : MutableLiveData<List<Record>> = MutableLiveData()

    var database = RecordDatabase.invoke()

    fun search(page: Int, str: String) {
        mRepository.search(page, str, searchLiveData)
    }

    fun getHotSearch() {
        mRepository.getHotSearch(hotSearchLiveData)
    }

    fun getHistorySearch() {
        mSearchHistory.postValue(database.recordDao().getAll())
    }

    fun addHistorySearch(str: String) {
        val datas = database.recordDao().getAll()
        val data = datas.filter { record ->
            return@filter record.name == str
        }.getOrElse(0) {
            return@getOrElse if (datas.size >= Constant.SEARCH_HISTORY_MAX) datas.get(0) else Record(
                -1,
                ""
            )
        }

        database.recordDao().delete(data)
        database.recordDao().insert(Record(0,str))
        mSearchHistory.postValue(database.recordDao().getAll())
    }

    fun clearHistorySearch(){
        val datas = database.recordDao().getAll()
        datas.forEach {
            database.recordDao().delete(it)
        }
        mSearchHistory.postValue(database.recordDao().getAll())
    }
}